<template>
  <div class="order-manage">
    <div class="header">
      <h2>订单管理</h2>
    </div>

    <table>
      <thead>
        <tr>
          <th>维修单号</th>
          <th>故障区域</th>
          <th>故障类型</th>
          <th>维修状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="order in orderList" :key="order.ListId">
          <td>{{ order.ListId }}</td>
          <td>{{ order.FaultArea }}</td>
          <td>{{ order.Faulttype }}</td>
          <td>{{ order.ListState }}</td>
          <td>
            <button class="detail-btn" @click="handleViewDetail(order.ListId)">
              查看详情
            </button>
            <button
              class="delete-btn-small"
              @click="handleDeleteOrder(order.ListId)"
            >
              删除
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 订单详情对话框 -->
    <div v-if="showDetailDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>订单详情</h3>
          <div class="close-btn" @click="handleCloseDialog">×</div>
        </div>
        <div v-if="orderDetail" class="detail-content">
          <div class="detail-item">
            <div class="detail-label">报修人电话</div>
            <div class="detail-value">{{ orderDetail.CusPhone }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">故障区域描述</div>
            <div class="detail-value">{{ orderDetail.AreaDescribe }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">故障具体描述</div>
            <div class="detail-value">{{ orderDetail.FaultDescribe }}</div>
          </div>
          <div class="detail-item">
            <div class="photo-list">
              <div
                v-for="(url, index) in photoUrls"
                :key="index"
                class="photo-item"
                @click="handlePreviewImage(url)"
              >
                <img
                  :src="getShowPhotoUrl(url)"
                  alt="故障图片"
                  class="fault-photo"
                />
                <div class="photo-overlay">点击查看大图</div>
              </div>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">操作</div>
            <div class="detail-actions">
              <div
                class="worker-select"
                v-if="!showAssignWorker && orderDetail?.ListState === '待维修'"
              >
                <button class="assign-btn" @click="handleShowAssign">
                  派工
                </button>
              </div>
              <div class="worker-select" v-if="showAssignWorker">
                <select v-model="selectedWorkerId">
                  <option value="" v-if="availableWorkers.length === 0">
                    无空闲工人
                  </option>
                  <option value="" v-else>请选择维修工</option>
                  <option
                    v-for="worker in availableWorkers"
                    :key="worker.维修工号"
                    :value="worker.维修工号"
                  >
                    {{ worker.维修工姓名 }} ({{ worker.维修工手机号 }})
                  </option>
                </select>
                <button
                  class="confirm-btn"
                  @click="handleAssign"
                  :disabled="availableWorkers.length === 0"
                >
                  确认派工
                </button>
                <button class="cancel-btn" @click="showAssignWorker = false">
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <div
      v-if="showImagePreview"
      class="preview-overlay"
      @click="showImagePreview = false"
    >
      <div class="preview-content">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
        <div class="preview-close" @click="showImagePreview = false">×</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

interface Order {
  ListId: number;
  FaultArea: string;
  Faulttype: string;
  ListState: string;
}

interface OrderDetail {
  CusPhone: string;
  AreaDescribe: string;
  FaultDescribe: string;
  FaultPhoto: string;
  ListState: string;
  FaultArea?: string;
  Faulttype?: string;
}

const orderList = ref<Order[]>([]);
const orderDetail = ref<OrderDetail | null>(null);
const showDetailDialog = ref(false);
const photoUrls = ref<string[]>([]);
const showImagePreview = ref(false);
const previewImageUrl = ref("");
const showAssignWorker = ref(false);
const selectedWorkerId = ref("");
const availableWorkers = ref<any[]>([]);
const currentOrderId = ref("");

// 获取订单列表
const fetchOrderList = async () => {
  try {
    const res = await fetch("http://8.140.225.174:5000/faultlist/manage");
    const data = await res.json();
    console.log("订单列表响应:", data);

    if (data.code === 200) {
      orderList.value = data.data;
      console.log("设置后的订单列表:", orderList.value);
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
  }
};

// 获取图片URL
const getPhotoUrls = async (listId: string) => {
  try {
    const res = await fetch(`http://8.140.225.174:5000/getphotourl/${listId}`);
    const data = await res.json();
    console.log("图片URL响应:", data);
    if (data.code === "200") {
      return data.data;
    }
    return [];
  } catch (error) {
    console.error("获取图片URL失败:", error);
    return [];
  }
};

// 转换为showphoto URL
const getShowPhotoUrl = (url: string) => {
  const parts = url.split("5000/");
  if (parts.length === 2) {
    const pathPart = parts[1];
    const showPhotoUrl = `http://8.140.225.174:5000/showphoto/${pathPart}`;
    console.log("转换后的showphoto URL:", showPhotoUrl);
    return showPhotoUrl;
  }
  return url;
};

// 获取维修工列表
const fetchWorkerList = async () => {
  try {
    const res = await fetch("http://8.140.225.174:5000/worker/managent");
    const data = await res.json();
    if (data.code === 200) {
      // 只显示空闲状态的维修工
      availableWorkers.value = data.data.filter(
        (worker: any) => worker.维修工状态 !== "忙碌"
      );
    }
  } catch (error) {
    console.error("获取维修工列表失败:", error);
  }
};

// 显示派工选择
const handleShowAssign = async () => {
  await fetchWorkerList();
  showAssignWorker.value = true;
};

// 派工处理
const handleAssign = async () => {
  if (!selectedWorkerId.value) {
    alert("请选择维修工");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("ListId", String(currentOrderId.value));
    formData.append("WorkerId", String(selectedWorkerId.value));

    const res = await fetch("http://8.140.225.174:5000/faultworkerlist", {
      method: "POST",
      body: formData,
    });
    const data = await res.json();

    if (data.code === 200) {
      alert("派工成功");
      showAssignWorker.value = false;
      selectedWorkerId.value = "";
      showDetailDialog.value = false;
      await fetchOrderList();
    } else {
      throw new Error(data.message || "派工失败");
    }
  } catch (error: any) {
    console.error("派工错误:", error);
    alert(error.message);
  }
};

// 删除订单
const handleDeleteOrder = async (listId: number) => {
  if (!confirm("确定要删除该订单吗？")) return;

  try {
    // 先从页面上移除该订单，防止重复点击
    orderList.value = orderList.value.filter(
      (order) => order.ListId !== listId
    );

    const res = await fetch(
      `http://8.140.225.174:5000/faultlist/manage/${listId}`,
      {
        method: "DELETE",
      }
    );
    const data = await res.json();

    if (data.code === 200) {
      if (showDetailDialog.value) {
        showDetailDialog.value = false;
      }
      await fetchOrderList(); // 刷新列表
      alert("删除成功");
    } else {
      // 如果删除失败，恢复列表
      await fetchOrderList();
      throw new Error(data.message || "删除失败");
    }
  } catch (error: any) {
    console.error("删除错误:", error);
    alert(error.message);
    await fetchOrderList(); // 发生错误时也刷新列表
  }
};

// 添加关闭对话框的处理函数
const handleCloseDialog = async () => {
  showDetailDialog.value = false;
  await fetchOrderList(); // 关闭对话框时刷新列表
};

// 修改查看详情函数
const handleViewDetail = async (listId: number) => {
  try {
    console.log("查看详情, listId:", listId);
    currentOrderId.value = String(listId); // 保存当前订单ID

    // 从列表中获取当前订单的状态
    const currentOrder = orderList.value.find(
      (order) => order.ListId === listId
    );
    const currentState = currentOrder ? currentOrder.ListState : "";

    const res = await fetch(
      `http://8.140.225.174:5000/faultlist_mrassageclrear/${listId}`
    );
    const data = await res.json();
    console.log("订单详情响应:", data);

    if (data.code === 200) {
      orderDetail.value = {
        ...data.data,
        ListState: currentState, // 使用从列表中获取的状态
      };
      console.log("设置的订单详情:", orderDetail.value);
      console.log("订单状态:", orderDetail.value?.ListState);

      if (orderDetail.value?.FaultPhoto) {
        photoUrls.value = await getPhotoUrls(orderDetail.value.FaultPhoto);
        console.log("获取到的图片URL列表:", photoUrls.value);
      } else {
        photoUrls.value = [];
      }

      showDetailDialog.value = true;
      showAssignWorker.value = false; // 重置派工状态
      selectedWorkerId.value = ""; // 重置选中的维修工
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
  }
};

// 处理图片预览
const handlePreviewImage = (url: string) => {
  previewImageUrl.value = getShowPhotoUrl(url);
  showImagePreview.value = true;
};

onMounted(() => {
  fetchOrderList();
});
</script>

<style scoped>
.order-manage {
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f5f5f5;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background-color: white;
  padding: 0;
  border-radius: 12px;
  min-width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
}

.dialog-header {
  background: #409eff;
  padding: 20px 24px;
  border-bottom: none;
  margin-bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  color: white;
  font-size: 20px;
  font-weight: 500;
}

.close-btn {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(180deg);
  color: white;
}

.detail-content {
  padding: 24px;
  max-height: calc(90vh - 70px);
  overflow-y: auto;
}

.detail-item {
  margin-bottom: 24px;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.detail-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.detail-content strong {
  min-width: 100px;
  color: #606266;
  font-weight: 500;
  margin-right: 16px;
}

.photos {
  margin-top: 20px;
}

.photo-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
  margin-top: 12px;
  padding: 0 12px;
}

.photo-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.photo-item:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.fault-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.photo-item:hover .photo-overlay {
  opacity: 1;
}

.dialog-actions {
  margin-top: 20px;
  text-align: right;
}

button {
  padding: 6px 12px;
  margin-left: 10px;
  cursor: pointer;
}

.detail-btn {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

.preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  backdrop-filter: blur(8px);
}

.preview-content {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.preview-close {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: white;
  font-size: 30px;
  cursor: pointer;
}

.detail-item {
  margin-bottom: 24px;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.detail-label {
  font-size: 15px;
  color: #409eff;
  margin-bottom: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.detail-label::before {
  content: "";
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.detail-value {
  background: white;
  padding: 16px;
  border-radius: 8px;
  font-size: 15px;
  line-height: 1.6;
}

.detail-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.worker-select {
  display: flex;
  gap: 10px;
  align-items: center;
}

.worker-select select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
  min-width: 200px;
}

.assign-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background-color: #67c23a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #909399;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: auto;
}

button:hover {
  opacity: 0.9;
}

.delete-btn-small {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 8px;
  font-size: 14px;
}

.delete-btn-small:hover {
  opacity: 0.9;
}
</style>
